package com.ithiema.edu.info.manager.utils;

import com.ithiema.edu.info.manager.domain.Persion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/*
    工具类
 */
public class Utils {
    //根据学号，学生类数组，返回索引
    public int InquireIndex(String id, Persion[] stus) {
        int index = -1;
        for (int i = 0; i < stus.length; i++) {
            if (null != stus[i] && stus[i].getId().equals(id)) {
                index = i;
            }
        }
        return index;
    }

    //判断数组中是否存在相同学号(String类型)
    public boolean seekIndex(String id, Persion[] stus) {
        int index = InquireIndex(id, stus);//利用已有工具判断
        if (index != -1) {
            return true;
        }
        return false;
    }

    //根据生日计算年龄
    public int getAge(String birthday)  {
        //创建SimpleDateFormat对象，设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
        //将字符串格式生日转为Date类型
        Date date_birthday = null;
        try {
            date_birthday = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal_birthday = new GregorianCalendar();
        //将生日设置为Calendar格式
        cal_birthday.setTime(date_birthday);
        //获取现在日历
        Calendar now_time = new GregorianCalendar();
        //根据现在与生日日历计算年龄
        //根据年计算
        int age = now_time.get(Calendar.YEAR)-cal_birthday.get(Calendar.YEAR);
        //根据月、日决定是否减一岁
        if(now_time.get(Calendar.MONTH)-cal_birthday.get(Calendar.MONTH)<0){
            age--;//月份没有达到生日月份，减一岁
        }
        if(now_time.get(Calendar.MONTH)-cal_birthday.get(Calendar.MONTH)==0){
            if(now_time.get(Calendar.DAY_OF_MONTH )-cal_birthday.get(Calendar.DAY_OF_MONTH )<0){
                age--;//月份相同，日没有达到，减一岁
            }
        }
        return age;
    }
}














